<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>失物招领平台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#F59E0B',
                        neutral: '#1F2937',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* 按钮样式 */
        .jump-btn {
            position: fixed; /* 固定定位，始终显示在页面右下角 */
            right: 20px; /* 距离右侧20像素 */
            bottom: 20px; /* 距离底部20像素 */
            padding: 12px 24px; /* 内边距 */
            background-color: #3a3a3a; /* 绿色背景 */
            color: white; /* 白色文字 */
            border: none; /* 无边框 */
            border-radius: 6px; /* 圆角 */
            cursor: pointer; /* 鼠标悬停显示手型 */
            font-size: 16px; /* 字体大小 */
            transition: background-color 0.3s; /* 背景色过渡效果 */
        }

        .jump-btn:hover {
            background-color: #45a049; /* 鼠标悬停时加深颜色 */
        }

        /* 左下角管理员登录按钮样式 */
        .admin-login-btn-bottom {
            position: fixed;
            left: 20px;
            bottom: 20px;
            padding: 12px 24px;
            background-color: #000;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        .admin-login-btn-bottom:hover {
            background-color: #333;
        }
    </style>
    <style type="text/tailwindcss">

        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg transform hover:-translate-y-1;
            }
            .admin-badge {
                @apply absolute top-3 right-3 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full;
            }
        }
         .jump-to-ai-btn {
            position: fixed;
            right: 20px;
            bottom: 20px;
            padding: 12px 24px;
            background-color: #007BFF; /* 蓝色背景 */
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        .jump-to-ai-btn:hover {
            background-color: #848f9c; /* 鼠标悬停时加深颜色 */
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-md sticky top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-search fa-flip-horizontal text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-neutral">失物招领平台</h1>
            </div>
            <div class="flex items-center space-x-3">
                <button id="add-item-btn" class="bg-primary text-white px-4 py-2 rounded-lg btn-hover flex items-center">
                    <i class="fa fa-plus mr-2"></i>添加物品
                </button>
                <button id="user-login-btn" class="bg-neutral text-white px-4 py-2 rounded-lg btn-hover flex items-center">
                    <i class="fa fa-user mr-2"></i><span id="user-text">用户登录</span>
                </button>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <!-- 搜索栏 -->
        <div class="mb-8 bg-white rounded-xl p-4 shadow-sm">
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-grow">
                    <input type="text" id="search-input" placeholder="搜索丢失物品..."
                        class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50">
                </div>
                <div class="flex items-center">
                    <select id="location-filter" class="px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <option value="">所有地点</option>
                        <option value="图书馆">图书馆</option>
                        <option value="教学楼">教学楼</option>
                        <option value="食堂">食堂</option>
                        <option value="宿舍">宿舍</option>
                        <option value="体育馆">体育馆</option>
                    </select>
                </div>
                <div>
                    <button id="search-btn" class="bg-primary text-white px-6 py-3 rounded-lg btn-hover flex items-center">
                        <i class="fa fa-search mr-2"></i>搜索
                    </button>
                </div>
            </div>
        </div>

        <!-- 物品列表 -->
        <div id="items-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <!-- 物品卡片将通过JavaScript动态添加 -->
        </div>

        <!-- 加载更多按钮 -->
        <div class="mt-10 text-center">
            <button id="load-more-btn" class="bg-white border border-gray-300 text-neutral px-6 py-3 rounded-lg btn-hover flex items-center mx-auto">
                <i class="fa fa-refresh mr-2"></i>加载更多
            </button>
        </div>
    </main>

    <!-- 添加物品模态框 -->
    <div id="add-item-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-6 w-full max-w-lg mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-neutral">添加丢失物品</h2>
                <button id="close-modal-btn" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <form id="add-item-form" enctype="multipart/form-data">
                <div class="mb-4">
                    <label for="item-name" class="block text-sm font-medium text-gray-700 mb-1">物品名称 <span class="text-red-500">*</span></label>
                    <input type="text" id="item-name" name="name" required
                        class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50">
                </div>
                <div class="mb-4">
                    <label for="item-description" class="block text-sm font-medium text-gray-700 mb-1">物品描述</label>
                    <textarea id="item-description" name="description" rows="3"
                        class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50"></textarea>
                </div>
                <div class="mb-4">
                    <label for="lost-location" class="block text-sm font-medium text-gray-700 mb-1">丢失地点 <span class="text-red-500">*</span></label>
                    <input type="text" id="lost-location" name="lost_location" required
                        class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50">
                </div>
                <div class="mb-4">
                    <label for="claim-location" class="block text-sm font-medium text-gray-700 mb-1">认领地点 <span class="text-red-500">*</span></label>
                    <input type="text" id="claim-location" name="claim_location" required
                        class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50">
                </div>
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-1">物品图片</label>
                    <div class="flex items-center justify-center w-full">
                        <label for="item-image" class="flex flex-col items-center justify-center w-full h-40 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 transition-all duration-300">
                            <div class="flex flex-col items-center justify-center pt-5 pb-6">
                                <i class="fa fa-cloud-upload text-3xl text-gray-400 mb-2"></i>
                                <p class="mb-2 text-sm text-gray-500"><span class="font-semibold">点击上传图片</span> 或拖放文件</p>
                                <p class="text-xs text-gray-500">PNG, JPG 或 GIF (最大 5MB)</p>
                            </div>
                            <input id="item-image" type="file" name="image" accept="image/*" class="hidden" />
                        </label>
                    </div>
                    <div id="image-preview" class="mt-2 hidden">
                        <img id="preview-img" src="" alt="预览图" class="max-h-32 rounded-lg">
                        <button type="button" id="remove-image-btn" class="mt-1 text-red-500 text-sm">
                            <i class="fa fa-times-circle"></i> 移除图片
                        </button>
                    </div>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancel-add-btn" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">取消</button>
                    <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg btn-hover">提交</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 物品详情模态框 -->
    <div id="item-details-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-6 w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto transform transition-all duration-300 scale-95 opacity-0" id="details-modal-content">
            <!-- 内容将通过JavaScript动态添加 -->
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-neutral text-white py-6">
        <div class="container mx-auto px-4 text-center">
            <p>&copy; 2025 失物招领平台 - 帮助找回您丢失的物品</p>
            <div class="mt-2 text-sm text-gray-400">
                <p>联系我们:bj3531781462@163.com</p>
            </div>
        </div>
<!--        <button class="jump-to-ai-btn" id="jump-to-ai-btn">-->
<!--            <i class="fa fa-robot mr-2"></i>AI客服-->
<!--        </button>-->
        <button class="admin-login-btn-bottom" id="admin-login-btn-bottom">
            <i class="fa fa-user-secret mr-2"></i>管理员登录
        </button>

    </footer>

    <script>
        // DOM元素
        const addItemBtn = document.getElementById('add-item-btn');
        const addItemModal = document.getElementById('add-item-modal');
        const modalContent = document.getElementById('modal-content');
        const closeModalBtn = document.getElementById('close-modal-btn');
        const cancelAddBtn = document.getElementById('cancel-add-btn');
        const addItemForm = document.getElementById('add-item-form');
        const itemImageInput = document.getElementById('item-image');
        const imagePreview = document.getElementById('image-preview');
        const previewImg = document.getElementById('preview-img');
        const removeImageBtn = document.getElementById('remove-image-btn');
        const itemsContainer = document.getElementById('items-container');
        const searchBtn = document.getElementById('search-btn');
        const searchInput = document.getElementById('search-input');
        const locationFilter = document.getElementById('location-filter');
        const loadMoreBtn = document.getElementById('load-more-btn');
        const userLoginBtn = document.getElementById('user-login-btn');
        const userText = document.getElementById('user-text');
        const itemDetailsModal = document.getElementById('item-details-modal');
        const detailsModalContent = document.getElementById('details-modal-content');
        const adminLoginBtnBottom = document.getElementById('admin-login-btn-bottom');

        // API基础URL
        const API_BASE_URL = 'http://localhost:5000/api';

        // 页码和每页数量
        let currentPage = 1;
        const itemsPerPage = 9;
        let isLoading = false;
        let hasMoreItems = true;
        let isUserLoggedIn = false;
        let isAdmin = false;

        // 初始化
        checkAdminStatus();
        checkUserStatus();

        // 打开模态框
        function openModal() {
            console.log('打开添加物品模态框');
            addItemModal.classList.remove('hidden');
            // 触发重排后添加动画类
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        // 关闭模态框
        function closeModal() {
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                addItemModal.classList.add('hidden');
                // 重置表单
                addItemForm.reset();
                imagePreview.classList.add('hidden');
            }, 300);
        }

        // 打开物品详情模态框
        function openDetailsModal() {
            itemDetailsModal.classList.remove('hidden');
            setTimeout(() => {
                detailsModalContent.classList.remove('scale-95', 'opacity-0');
                detailsModalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        // 关闭物品详情模态框
        function closeDetailsModal() {
            detailsModalContent.classList.remove('scale-100', 'opacity-100');
            detailsModalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                itemDetailsModal.classList.add('hidden');
            }, 300);
        }

        // 图片预览
        itemImageInput.addEventListener('change', function () {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    previewImg.src = e.target.result;
                    imagePreview.classList.remove('hidden');
                }
                reader.readAsDataURL(this.files[0]);
            }
        });

        // 移除图片
        removeImageBtn.addEventListener('click', function () {
            itemImageInput.value = '';
            imagePreview.classList.add('hidden');
        });

        // 添加物品表单提交
        addItemForm.addEventListener('submit', async function (e) {
            e.preventDefault();

            if (!isUserLoggedIn) {
                // 如果未登录，跳转到登录界面
                window.location.href = 'login.html';
                return;
            }

            // 收集表单数据
            const formData = new FormData(this);

            try {
                // 显示加载状态
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>提交中...';

                // 发送请求
                const response = await fetch(`${API_BASE_URL}/items`, {
                    method: 'POST',
                    credentials: 'include',  // 关键修改：包含cookie
                    body: formData
                });

                if (response.ok) {
                    const data = await response.json();
                    // 添加成功，关闭模态框
                    closeModal();
                    // 显示成功通知
                    showNotification('物品添加成功！', 'success');
                    // 刷新物品列表
                    currentPage = 1;
                    hasMoreItems = true;
                    fetchItems();
                } else {
                    throw new Error('提交失败，请重试（请检查登陆状态）');
                }
            } catch (error) {
                showNotification(error.message, 'error');
            } finally {
                // 恢复按钮状态
                const submitBtn = addItemForm.querySelector('button[type="submit"]');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        });

        // 检查管理员状态
        async function checkAdminStatus() {
            try {
                const response = await fetch(`${API_BASE_URL}/admin/status`, {
                    credentials: 'include'  // 关键修改：包含cookie
                });
                if (response.ok) {
                    const data = await response.json();
                    isAdmin = data.admin;
                    updateAdminUI();
                }
            } catch (error) {
                console.error('检查管理员状态失败:', error);
            }
        }

        // 检查用户状态
        async function checkUserStatus() {
            try {
                const response = await fetch(`${API_BASE_URL}/user/status`, {
                    credentials: 'include'  // 包含cookie
                });
                if (response.ok) {
                    const data = await response.json();
                    isUserLoggedIn = data.logged_in;
                    updateUserUI();
                }
            } catch (error) {
                console.error('检查用户状态失败:', error);
            }
        }

        // 更新管理员UI
        function updateAdminUI() {
            if (isAdmin) {
                userText.textContent = '退出登录';
                userLoginBtn.classList.remove('bg-neutral');
                userLoginBtn.classList.add('bg-red-500');
            } else {
                userText.textContent = '用户登录';
                userLoginBtn.classList.remove('bg-red-500');
                userLoginBtn.classList.add('bg-neutral');
            }
        }

        // 更新用户UI
        function updateUserUI() {
            if (isUserLoggedIn) {
                userText.textContent = '退出登录';
                userLoginBtn.classList.remove('bg-neutral');
                userLoginBtn.classList.add('bg-red-500');
            } else {
                userText.textContent = '用户登录';
                userLoginBtn.classList.remove('bg-red-500');
                userLoginBtn.classList.add('bg-neutral');
            }
        }

        // 用户登录/退出切换
        userLoginBtn.addEventListener('click', function () {
            if (isUserLoggedIn || isAdmin) {
                logout();
            } else {
                window.location.href = 'login.html';
            }
        });

        // 管理员登录按钮点击事件
        adminLoginBtnBottom.addEventListener('click', function () {
            window.location.href = 'admin_login.html'; // 假设管理员登录页面为 admin_login.html
        });

        // 登出
        async function logout() {
            try {
                const response = await fetch(`${API_BASE_URL}/logout`, {
                    method: 'POST',
                    credentials: 'include'  // 关键修改：包含cookie
                });

                if (response.ok) {
                    isUserLoggedIn = false;
                    isAdmin = false;
                    updateAdminUI();
                    updateUserUI();
                    showNotification('已登出', 'info');
                    // 刷新物品列表，隐藏删除按钮
                    currentPage = 1;
                    hasMoreItems = true;
                    fetchItems();
                } else {
                    throw new Error('登出失败，请重试');
                }
            } catch (error) {
                showNotification(error.message, 'error');
            }
        }

        // 显示通知
        function showNotification(message, type = 'info') {
            // 创建通知元素
            const notification = document.createElement('div');
            notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full opacity-0 ${
                type === 'success' ? 'bg-green-50 text-green-800 border-l-4 border-green-400' :
                    type === 'error' ? 'bg-red-50 text-red-800 border-l-4 border-red-400' :
                        'bg-blue-50 text-blue-800 border-l-4 border-blue-400'
            }`;

            // 设置图标和消息
            const icon = type === 'success' ? 'fa-check-circle' :
                type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle';
            notification.innerHTML = `
                <div class="flex items-center">
                    <i class="fa ${icon} mr-3 text-lg"></i>
                    <span>${message}</span>
                </div>
            `;

            // 添加到页面
            document.body.appendChild(notification);

            // 显示通知
            setTimeout(() => {
                notification.classList.remove('translate-x-full', 'opacity-0');
                notification.classList.add('translate-x-0', 'opacity-100');
            }, 10);

            // 自动关闭
            setTimeout(() => {
                notification.classList.remove('translate-x-0', 'opacity-100');
                notification.classList.add('translate-x-full', 'opacity-0');
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }

        // 搜索物品
        searchBtn.addEventListener('click', function () {
            currentPage = 1;
            hasMoreItems = true;
            fetchItems();
        });

        // 加载更多物品
        loadMoreBtn.addEventListener('click', function () {
            if (!isLoading && hasMoreItems) {
                currentPage++;
                fetchItems(true);
            }
        });

        // 回车键触发搜索
        searchInput.addEventListener('keyup', function (event) {
            if (event.key === 'Enter') {
                searchBtn.click();
            }
        });

        // 获取物品列表
        async function fetchItems(append = false) {
            if (isLoading) return;

            isLoading = true;
            if (!append) {
                itemsContainer.innerHTML = '';
                loadMoreBtn.innerHTML = '<i class="fa fa-refresh mr-2"></i>加载更多';
            } else {
                // 显示加载状态
                loadMoreBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>加载中...';
            }

            try {
                const searchTerm = searchInput.value.trim();
                const location = locationFilter.value;

                let url = `${API_BASE_URL}/items`;
                const params = new URLSearchParams();
                params.append('page', currentPage);
                params.append('limit', itemsPerPage);
                if (searchTerm) params.append('search', searchTerm);
                if (location) params.append('location', location);

                if (params.toString()) {
                    url += '?' + params.toString();
                }

                // 发送请求，包含cookie
                const response = await fetch(url, {
                    credentials: 'include'
                });

                if (!response.ok) throw new Error('获取物品列表失败');

                const data = await response.json();
                const items = data.items || [];

                // 没有更多物品
                if (items.length < itemsPerPage) {
                    hasMoreItems = false;
                    loadMoreBtn.innerHTML = '<i class="fa fa-check mr-2"></i>没有更多物品了';
                    loadMoreBtn.disabled = true;
                } else {
                    loadMoreBtn.innerHTML = '<i class="fa fa-refresh mr-2"></i>加载更多';
                    loadMoreBtn.disabled = false;
                }

                // 添加物品卡片
                if (items.length === 0 && !append) {
                    itemsContainer.innerHTML = `
                        <div class="col-span-full text-center py-12">
                            <div class="text-gray-400 text-5xl mb-4">
                                <i class="fa fa-search"></i>
                            </div>
                            <h3 class="text-xl font-medium text-gray-700 mb-2">没有找到匹配的物品</h3>
                            <p class="text-gray-500">尝试使用不同的关键词或地点筛选</p>
                        </div>
                    `;
                } else {
                    items.forEach(item => {
                        const card = createItemCard(item);
                        itemsContainer.appendChild(card);
                    });
                }
            } catch (error) {
                showNotification(error.message, 'error');
            } finally {
                isLoading = false;
            }
        }

        // 创建物品卡片
        function createItemCard(item) {
            const card = document.createElement('div');
            card.className = 'bg-white rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-shadow duration-300 card-shadow group';

            // 图片部分
            let imageUrl = item.image_url;
            if (imageUrl && !imageUrl.startsWith('http')) {
                // 处理相对路径的图片URL
                imageUrl = `http://localhost:5000${imageUrl}`;
            } else {
                // 默认图片
                imageUrl = 'https://picsum.photos/seed/lostitem/400/300';
            }

            const imageContainer = document.createElement('div');
            imageContainer.className = 'relative h-48 overflow-hidden';
            const image = document.createElement('img');
            image.src = imageUrl;
            image.alt = item.name;
            image.className = 'w-full h-full object-cover transition-transform duration-500 group-hover:scale-110';
            imageContainer.appendChild(image);

            // 物品状态标签
            const statusBadge = document.createElement('div');
            statusBadge.className = 'absolute top-3 left-3 bg-accent text-white text-xs font-bold px-2 py-1 rounded-full';
            statusBadge.textContent = '丢失';
            imageContainer.appendChild(statusBadge);

            // 如果是管理员，添加管理员标签
            if (isAdmin) {
                const adminBadge = document.createElement('div');
                adminBadge.className = 'admin-badge';
                adminBadge.innerHTML = '<i class="fa fa-user-secret mr-1"></i> 管理';
                imageContainer.appendChild(adminBadge);
            }

            // 卡片内容
            const content = document.createElement('div');
            content.className = 'p-5';

            const name = document.createElement('h3');
            name.className = 'text-lg font-bold text-neutral mb-2';
            name.textContent = item.name;

            const description = document.createElement('p');
            description.className = 'text-gray-600 text-sm mb-4 line-clamp-2';
            description.textContent = item.description || '没有描述';

            const locations = document.createElement('div');
            locations.className = 'grid grid-cols-2 gap-3 mb-4';

            const lostLocation = document.createElement('div');
            lostLocation.className = 'flex items-center text-sm text-gray-500';
            lostLocation.innerHTML = '<i class="fa fa-map-marker-alt mr-2 text-primary"></i> ' + item.lost_location;

            const claimLocation = document.createElement('div');
            claimLocation.className = 'flex items-center text-sm text-gray-500';
            claimLocation.innerHTML = '<i class="fa fa-map-pin mr-2 text-secondary"></i> ' + item.claim_location;

            locations.appendChild(lostLocation);
            locations.appendChild(claimLocation);

            // 按钮区域
            const buttons = document.createElement('div');
            buttons.className = 'flex space-x-3';

            // 查看详情按钮
            const viewBtn = document.createElement('button');
            viewBtn.className = 'flex-1 bg-primary/10 text-primary font-medium py-2 px-4 rounded-lg hover:bg-primary/20 transition-colors duration-300 flex items-center justify-center';
            viewBtn.innerHTML = '<i class="fa fa-eye mr-2"></i> 查看详情';

            buttons.appendChild(viewBtn);

            // 如果是管理员，添加删除按钮
            if (isAdmin) {
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'bg-red-500 text-white font-medium py-2 px-4 rounded-lg hover:bg-red-600 transition-colors duration-300 flex items-center justify-center';
                deleteBtn.innerHTML = '<i class="fa fa-trash mr-2"></i> 删除';
                deleteBtn.addEventListener('click', function () {
                    deleteItem(item.id);
                });
                buttons.appendChild(deleteBtn);
            }

            content.appendChild(name);
            content.appendChild(description);
            content.appendChild(locations);
            content.appendChild(buttons);

            card.appendChild(imageContainer);
            card.appendChild(content);

            // 添加点击事件
            viewBtn.addEventListener('click', function () {
                showItemDetails(item);
            });

            return card;
        }

        // 删除物品
        async function deleteItem(itemId) {
            if (!confirm('确定要删除这个物品吗？此操作不可撤销。')) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE_URL}/items/${itemId}`, {
                    method: 'DELETE',
                    credentials: 'include'  // 关键修改：包含cookie
                });

                if (response.ok) {
                    showNotification('物品删除成功！', 'success');
                    // 刷新物品列表
                    currentPage = 1;
                    hasMoreItems = true;
                    fetchItems();
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '删除失败，请重试');
                }
            } catch (error) {
                showNotification(error.message, 'error');
            }
        }

        // 显示物品详情
        function showItemDetails(item) {
            // 清空模态框内容
            detailsModalContent.innerHTML = '';

            // 模态框头部
            const modalHeader = document.createElement('div');
            modalHeader.className = 'flex justify-between items-center mb-4';

            const title = document.createElement('h2');
            title.className = 'text-xl font-bold text-neutral';
            title.textContent = item.name;

            const closeBtn = document.createElement('button');
            closeBtn.className = 'text-gray-500 hover:text-gray-700';
            closeBtn.innerHTML = '<i class="fa fa-times text-xl"></i>';
            closeBtn.addEventListener('click', closeDetailsModal);

            modalHeader.appendChild(title);
            modalHeader.appendChild(closeBtn);

            // 模态框内容
            const modalBody = document.createElement('div');

            // 图片区域
            const imageContainer = document.createElement('div');
            imageContainer.className = 'mb-6 rounded-xl overflow-hidden';

            let imageUrl = item.image_url;
            if (imageUrl && !imageUrl.startsWith('http')) {
                imageUrl = `http://localhost:5000${imageUrl}`;
            } else {
                imageUrl = 'https://picsum.photos/seed/lostitem/800/500';
            }

            const image = document.createElement('img');
            image.src = imageUrl;
            image.alt = item.name;
            image.className = 'w-full h-auto rounded-xl';

            imageContainer.appendChild(image);

            // 物品信息
            const infoContainer = document.createElement('div');
            // 这里可以继续添加物品信息的显示代码
            // ...

            modalBody.appendChild(imageContainer);
            modalBody.appendChild(infoContainer);

            detailsModalContent.appendChild(modalHeader);
            detailsModalContent.appendChild(modalBody);

            openDetailsModal();
        }

        // 绑定添加物品按钮的点击事件
        addItemBtn.addEventListener('click', openModal);

        // 关闭模态框按钮点击事件
        closeModalBtn.addEventListener('click', function () {
            closeModal();
        });
    </script>
</body>
</html>